package com.ng.common.scheduling;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.JsonKit;
import com.ng.biz.service.IMqttClient;
import com.ng.common.util.DateUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@EnableScheduling
public class SysScheduling {

	@Autowired
	private IMqttClient mqttClientImpl;


	@Scheduled(fixedRate = 1 * 1000)
	@Async
	public void receive() {
		int count = mqttClientImpl.getAndSet(0);
		if (count != 0) {
			JSONObject payload = new JSONObject();
			payload.put("time", DateUtil.getFormatDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd HH:mm:ss"));
			payload.put("total", mqttClientImpl.getAndSet(0));
			mqttClientImpl.useSysPublish("/sys/mqtt/receive/message/ms", JsonKit.toJson(payload), 2, true);
		}
	}

	@Scheduled(fixedRate = 1 * 1000)
	@Async
	public void send() {
		int count = mqttClientImpl.getSendAndSet(0);
		if (count != 0) {
			JSONObject payload = new JSONObject();
			payload.put("time", DateUtil.getFormatDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd HH:mm:ss"));
			payload.put("total", mqttClientImpl.getSendAndSet(0));
			mqttClientImpl.useSysPublish("/sys/mqtt/send/message/ms", JsonKit.toJson(payload), 2, true);
		}
	}

	
	@Scheduled(fixedRate = 20 * 1000)
	@Async
	public void sendTest() {
		JSONObject payload = new JSONObject();		
		JSONObject item = new JSONObject();
		item.put("card_id", "Test_001");
		payload.put("123456", item);
		item.put("time", DateUtil.getFormatDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd HH:mm:ss"));
		item.put("total", mqttClientImpl.getSendAndSet(0));
		mqttClientImpl.useSysPublish("/sys/mqtt/send/test", JsonKit.toJson(payload), 2, true);
	}
	
}
